package com.waqu.common.utils.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @Title NetUtils.java
 * @Package com.waqu.common.utils.net
 * @author Administrator
 * @date 2015年7月30日 下午2:24:20
 * @version V1.0
 */
public class INetTools {

	private static InetAddress inetAddress() {
		try {
			InetAddress ip = null;
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> ips = ni.getInetAddresses();
				while (ips.hasMoreElements()) {
					ip = ips.nextElement();
					if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
						return ip;
					}
				}
			}
		} catch (SocketException e) {
		}
		return null;
	}

	/** 获取本机IP */
	public static String localNetAddress() {
		InetAddress inet = inetAddress();
		return null != inet ? inet.getHostAddress() : "127.0.0.1";
	}

	// 获取MAC地址的方法
	public static String MACAddress() {
		InetAddress inet = inetAddress();
		if (null != inet) {
			try {
				byte[] mac = NetworkInterface.getByInetAddress(inet).getHardwareAddress();
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < mac.length; i++) {
					if (i != 0) {
						sb.append("-");
					}
					String s = Integer.toHexString(mac[i] & 0xFF);
					sb.append(s.length() == 1 ? 0 + s : s);
				}
				// 把字符串所有小写字母改为大写成为正规的mac地址并返回
				return sb.toString().toUpperCase();
			} catch (Exception e) {
			}
		}
		return "00-00-00-00-00";
	}

	/** 获取本机名称 */
	public static String localName() {
		InetAddress inet = inetAddress();
		return null != inet ? inet.getHostName() : "";
	}
}
